package site.yunnong.atvris.portal.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.dfa.SensitiveUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
 * 铭感词过滤工具
 * @author zjh
 * @date 2021/9/8 16:53
 */
@Slf4j
@Component
public class SensitiveFilter {
    
    @PostConstruct
    public void init() {
        log.info("加载敏感词文件...");
        try (
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        ) {
            List<String> keywords = new ArrayList<>();
            String keyword;
            while ((keyword = reader.readLine()) != null) {
                // 添加到前缀树
                keywords.add(keyword);
            }
            SensitiveUtil.init(keywords);
            log.info("加载敏感词文件完成");
        } catch (IOException e) {
            log.error("加载敏感词文件失败: " + e.getMessage());
        }
        
//        URL path = ResourceUtil.getResource("sensitive-words.txt");
//        File file = FileUtil.file(path);
//        FileReader reader = new FileReader(file);
//        SensitiveUtil.init(reader.readLines());
//        log.info("加载敏感词文件完成");
    }
    
    public static String sensitiveWordFiltering(String text) {
        List<String> matchAll = SensitiveUtil.getFindedAllSensitive(text, false, false);
        if (CollectionUtils.isNotEmpty(matchAll)) {
            for (String match : matchAll) {
                StringBuilder replace = new StringBuilder();
                for (int i = 0; i < StringUtils.length(match); i++) {
                    replace.append("*");
                }
                text = StringUtils.replace(text, match, replace.toString());
            }
        }
        return text;
    }
    
    public static boolean containsSensitive(String text) {
        return SensitiveUtil.containsSensitive(text);
    }

    public static void main(String[] args) {
        log.info("加载敏感词文件...");
        URL path = ResourceUtil.getResource("sensitive-words.txt");
        File file = FileUtil.file(path);
        FileReader reader = new FileReader(file);
        SensitiveUtil.init(reader.readLines());
        log.info("加载敏感词文件完成");
        String str = sensitiveWordFiltering("我草");
        System.out.println(str);
    }
}
